package com.mgm.custom.applift;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mgm.base.ConverAdRoot;
import com.mgm.pojo.Advertisement;
import com.mgm.pojo.Creative;
import com.mgm.utils.RandomCodeUtils;
import com.mgm.utils.UUIDUtil;

public class AppliftConverToAdvertisement {
	
	private static final String[] COUNTRY_CODE = {"IN","ID","US","JP","KR","VN","BR"};
	private static final BigDecimal PERCENT = BigDecimal.valueOf(1000);
	
	public static JSONArray checkOffer(JSONArray jsonArray) {
		List<String> asList = Arrays.asList(COUNTRY_CODE);
		/**
		 * offerid,offername,trackingurl,payouttype,payout,geo,packagename,os／platform
		 */
		Iterator<Object> it = jsonArray.iterator();
		while(it.hasNext()) {
			JSONObject j_obj = (JSONObject) it.next();
			JSONObject j_appdetails = j_obj.getJSONObject("app_details");
			String packageName = j_appdetails.getString("bundle_id"); //packagename包名(iOS格式：1014949597；Android格式：amaro.amaroandroid)
			String platform = j_appdetails.getString("platform");
			if(StringUtils.isEmpty(packageName) || StringUtils.isEmpty(platform)) {
				it.remove(); //删除
				continue;
			}
			
			JSONArray j_offers = j_obj.getJSONArray("offers");
			Iterator<Object> offer_it = j_offers.iterator();
			while(offer_it.hasNext()) {
				JSONObject offerObj = (JSONObject) offer_it.next();
				String offerid = offerObj.getString("offer_id");
				String offername = offerObj.getString("offer_name");
				String trackingurl = offerObj.getString("click_url");
				String payouttype = offerObj.getString("goal_type"); //cpi/cpa
				JSONArray geoArr = offerObj.getJSONArray("geo_targeting"); //geo数组
				boolean isRemoveGeo = true;
				for (int i = 0; i < geoArr.size(); i++) {
					JSONObject geoObj = geoArr.getJSONObject(i);
					if (geoObj != null && asList.contains(geoObj.getString("country_code"))) {
						isRemoveGeo = false;
					}
				}
				boolean isRemovePayout = false;
				JSONArray payoutArr = offerObj.getJSONArray("goal_payouts");
				if(payoutArr == null || payoutArr.get(0) == null || payoutArr.getJSONObject(0).getInteger("payout") == null) {
					isRemovePayout = true;
				}
				
				if(StringUtils.isEmpty(offerid) || StringUtils.isEmpty(offername) 
						|| StringUtils.isEmpty(trackingurl) || StringUtils.isEmpty(payouttype)
						|| isRemoveGeo || isRemovePayout) {
					offer_it.remove(); //删除
				}
			}
		}
		return jsonArray;
	}
	
	public static ConverAdRoot toAdvertisement(Integer aderId, JSONArray jsonArray) {
		if(jsonArray == null) {
			return null;
		}
		ConverAdRoot root = new ConverAdRoot();
		root.setAdId(aderId);
		Date curTime = new Date();
    	DateTime jodaTime = new DateTime(curTime);
    	DateTime n = jodaTime.plusHours(2);
    	
		int size = jsonArray.size(); //数组大小
		Advertisement adment = null;
//		Creative creative = null;
		List<Advertisement> adlist = new ArrayList<>(size);
		Map<String, Advertisement> admap = new HashMap<>(size);
//		Map<String, Creative> ctmap = new HashMap<>(size);
		List<String> adIds = new ArrayList<>(size);
//		List<Creative> clist = new ArrayList<>(size);
		for (int i = 0; i < size; i++) { //循环app_details+offers
			JSONObject j_obj = jsonArray.getJSONObject(i);
			JSONObject j_appdetails = j_obj.getJSONObject("app_details");
			
			JSONArray j_offers = j_obj.getJSONArray("offers"); //check的时候有可能都筛选空了（"offers":[]）
			for (int j = 0; j < j_offers.size(); j++) {
				JSONObject offerObj = j_offers.getJSONObject(j);
				if (offerObj == null) continue;
				JSONArray geoArr = offerObj.getJSONArray("geo_targeting"); //geo数组
				StringBuilder geosb = new StringBuilder();
				String geoStr = "";
				for (int k = 0; k < geoArr.size(); k++) {
					JSONObject geoObj = geoArr.getJSONObject(k);
					geosb.append(geoObj.getString("country_code")+",");
				}
				if(geosb.toString().endsWith(",")) geoStr = geosb.substring(0, geosb.length()-1);
				
				JSONArray payoutArr = offerObj.getJSONArray("goal_payouts"); //单价(数组)
				Integer payoutInt = payoutArr.getJSONObject(0).getInteger("payout");
				
				JSONArray creativesArr = offerObj.getJSONArray("creatives"); //creatives
				String url = "";
				for (int k = 0; k < creativesArr.size(); k++) {
					JSONObject creativeObj = creativesArr.getJSONObject(k);
					if(creativeObj!=null && creativeObj.getString("creative_type").equals("icon")) {
						url = creativeObj.getString("url");
					}
				}
				if(url.length()==0) {
					for (int k = 0; k < creativesArr.size(); k++) {
						JSONObject creativeObj = creativesArr.getJSONObject(k);
						if(creativeObj!=null && creativeObj.getString("creative_type").equals("banner")) {
							url = creativeObj.getString("url");
						}
					}
				}
				
				//----广告===========================
				adment = new Advertisement();
//				String offerid = j_obj.getString("id")+RandomCodeUtils.randomNumeric(8); //系统生成offerid
				adment.setAdv_id(aderId); 
//				adment.setOfferId(offerid); 
				adment.setOfferName(offerObj.getString("offer_name"));
				adment.setEnabled(true);
				
				adment.setPay_type(offerObj.getString("goal_type").toLowerCase()); //cpi/cpa
				adment.setPay_price(BigDecimal.valueOf(payoutInt).divide(PERCENT, 2, RoundingMode.DOWN)); //待确认
				adment.setCurrency("USD"); //默认USD
				adment.setRequires(null); //暂不做控制
				
				adment.setOs(j_appdetails.getString("platform"));
				adment.setCountries(geoStr);
				adment.setClick_url(offerObj.getString("click_url"));
				adment.setCarrier(null);
				adment.setOs_version(j_appdetails.getString("version"));
				adment.setExcitation(offerObj.getBoolean("incent"));
	    		adment.setExpire_date(n.toDate());
	    		adment.setTrackingsolution(null);
	    		adment.setKpi(null);
	    		
	    		adment.setCap_type(null);
	    		adment.setConvernsion_cap(null);
	    		adment.setDaily_conversion_cap(null);
	    		adment.setMonth_conversion_cap(null);
	    		adment.setPayout_cap(null);
	    		adment.setDaily_payout_cap(null);
	    		adment.setMonth_payout_cap(null);
	    		
	    		adment.setAppname(null);
	    		adment.setPkgname(j_appdetails.getString("bundle_id")); //packagename包名(iOS格式：1014949597；Android格式：amaro.amaroandroid)
	    		adment.setPreview_url(null);
	    		
	    		adment.setPremium(null);
	    		adment.setPremium_price(null);
	    		adment.setIcon(url); //.....
	    		adment.setStart_at(curTime);
	    		adment.setEnd_at(null);
	    		adment.setUpdate_time(curTime);
	    		adment.setCounter(0); //默认0
	    		adment.setP1(offerObj.getString("offer_id")); //上游offerid
	    		
	    		adlist.add(adment);
	    		admap.put(adment.getP1(), adment);
	    		adIds.add(offerObj.getString("offer_id"));
			}
			
		}
		root.setAdlist(adlist);
		root.setAdmap(admap);
		root.setAdids(adIds);
		
//		root.setCtlist(clist);
//		root.setCtmap(ctmap);
		return root;
	}

}
